package com.yili.controller.api;

import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.yili.controller.ApiResponse;

import com.yili.printer.service.PrintService;
import com.yili.printer.generator.Generator;
import com.yili.printer.generator.ZplLabelGenerator;

@RestController
@RequestMapping("/api")
public class PrintController {

    private static final Logger logger = LogManager.getLogger(PrintController.class);

    @Autowired
    private PrintService printService;

    /**
     * 批量打印标签接口
     * 
     * @param productionDate  生产日期
     * @param productionBatch 生产批次
     * @param startSerial     开始序号
     * @param endSerial       结束序号
     * @return 打印结果
     */
    @PostMapping("/print")
    public ApiResponse<Map<String, Integer>> print(
            @RequestParam String productionDate,
            @RequestParam String productionBatch,
            @RequestParam int startSerial,
            @RequestParam int endSerial) {

        try {
            // 参数验证
            if (startSerial > endSerial) {
                return new ApiResponse<>(400, "开始序号不能大于结束序号", false, null);
            }

            if (startSerial < 1 || endSerial < 1) {
                return new ApiResponse<>(400, "序号必须大于0", false, null);
            }

            // 执行批量打印操作
            int successCount = 0;
            int totalCount = endSerial - startSerial + 1;

            for (int serial = startSerial; serial <= endSerial; serial++) {
                try {
                    // 创建打印数据Map，支持不同标签的不同元素需求
                    Map<String, String> printData = new HashMap<>();
                    printData.put("productionDate", productionDate);
                    printData.put("productionBatch", productionBatch);
                    printData.put("serial", String.valueOf(serial));

                    // 调用printLabel方法，PrintService内部会处理连接检查和重连
                    Generator generator = new ZplLabelGenerator();
                    printService.printLabel(printData, generator);
                    successCount++;
                } catch (Exception e) {
                    logger.error("打印标签失败，生产日期: {}, 生产批次: {}, 序号: {}, 错误信息: {}",
                            productionDate, productionBatch, serial, e.getMessage());
                }
            }

            // 根据打印结果设置返回信息
            Map<String, Integer> resultData = new HashMap<>();
            resultData.put("printCount", successCount);
            resultData.put("totalCount", totalCount);

            if (successCount == totalCount) {
                return new ApiResponse<>(200, "批量打印成功", true, resultData);
            } else if (successCount > 0) {
                return new ApiResponse<>(206, String.format("批量打印部分失败，成功: %d/%d", successCount, totalCount), false,
                        resultData);
            } else {
                return new ApiResponse<>(500, "打印失败，请检查打印机连接或稍后重试", false, null);
            }

        } catch (Exception e) {
            return new ApiResponse<>(500, "打印过程中发生异常: " + e.getMessage(), false, null);
        }
    }
}